//
//  WithdrawViewModel.m
//  CBT
//
//  Created by Mr.Zhang on 2018/12/4.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "WithdrawViewModel.h"
#import "UserManager.h"
#import "LoginManager.h"
#import "ZFPwdView.h"
#import "JHUIAlertView.h"

@interface WithdrawViewModel ()
@property (nonatomic, weak) UITextField *rechargeTF;
@property (nonatomic, strong) JHUIAlertView *alertView;
@end

@implementation WithdrawViewModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUp];
    }
    return self;
}

- (void)setUp{
    
    @weak(self);
    
    _drawRate = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            [UserManager getUserDrawRateWithBlock:^(id data, HttpRequestResult result, NSString *msg) {
                if (result == kHttpRequestResultNormal) {
                    [subscriber sendNext:@{@"drawRate":[data[@"data"]objectForKey:@"drawRate"],@"ETHPrice":[data[@"data"]objectForKey:@"ETHPrice"]}];
                    [subscriber sendCompleted];
                }else{
                    [HFStatusView showFailureMessage:msg];
                    [subscriber sendError:nil];
                    [subscriber sendCompleted];
                }
            }];
            
            return [RACDisposable disposableWithBlock:^{
                NSLog(@"获取用户提现手续费操作结束了");
            }];
        }];
    }];
    
    _withdrawCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
//        if ([NSString isBlankString:input[@"value"]]) {
//            [HFStatusView showFailureMessage:kLocalizedString(@"请输入提币数量",nil)];
//            return [RACSignal error:nil];
//        }else if([input[@"value"]intValue] <= 0){
//            [HFStatusView showFailureMessage:kLocalizedString(@"提币数额必须大于0",nil)];
//            return [RACSignal error:nil];
//        }else if ([NSString isBlankString:input[@"walleatAdress"]]){
//            [HFStatusView showFailureMessage:kLocalizedString(@"请输入AKB地址",nil)];
//            return [RACSignal error:nil];
//        }else if (![NSString isETHAddress:[NSString stringWithFormat:@"%@",input[@"walleatAdress"]]]){
//            [HFStatusView showFailureMessage:kLocalizedString(@"请输入正确的ETH地址",nil)];
//            return [RACSignal error:nil];
//        }else
        if ([[NSString stringWithFormat:@"%@",input[@"value"]]floatValue] > [[CBTLocalUserManager sharedInstance].userAsset floatValue]){
            [HFStatusView showFailureMessage:kLocalizedString(@"数量不足",nil)];
            return [RACSignal error:nil];
        }
        
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            NSString *area = [[NSUserDefaults standardUserDefaults] objectForKey:@"area"];
            //检查是否设置过支付密码、是否实名认证
            [LoginManager phoneaAndEmailLoginWithID:[NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone] ? [CBTLocalUserManager sharedInstance].userEmail : [CBTLocalUserManager sharedInstance].userPhone isPhone:![NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone]  pwd:HEFANTV_UserPassWord area:area block:^(id data, HttpRequestResult result, NSString *msg) {
                if (result == kHttpRequestResultNormal) {
                    
                    [[NSUserDefaults standardUserDefaults]setObject:[data[@"data"]objectForKey:@"token"] forKey:HEFANTV_TOKEN];
                    [[NSUserDefaults standardUserDefaults]synchronize];
                    [[CBTLocalUserManager sharedInstance] saveALLUserInfoDic:data];
                    
                    [self_weak_.viewControllers stopLoading];
                    
//                    if ([[data[@"data"]objectForKey:@"flag"]intValue] != 1) {
//                        [HFStatusView showFailureMessage:kLocalizedString(@"请先实名认证", nil)];
//                        return;
//                    }else
                    if ([[data[@"data"]objectForKey:@"status"]intValue] == 0) {
                        [HFStatusView showFailureMessage:kLocalizedString(@"请先设置支付密码", nil)];
                        return;
                    }
                    
                    //输入支付
                    [ZFPwdView showZFPwdViewWithInputCompletedBlock:^(NSString * _Nonnull password) {
                        [self_weak_.viewControllers startClearBgColorLoading];
                        //校验支付密码
                        [UserManager checkPayPassWordWithUserID:[CBTLocalUserManager sharedInstance].userId passWord:password block:^(id data, HttpRequestResult result, NSString *msg) {
                            if (result == kHttpRequestResultNormal && [[data[@"data"]objectForKey:@"result"]boolValue] == YES) {
                                //提现
                                [UserManager userdrawMoneyByAlipayWithUserId:[CBTLocalUserManager sharedInstance].userId walleatAdress:input[@"walleatAdress"] value:input[@"value"] block:^(id data, HttpRequestResult result, NSString *msg) {
                                    if (result == kHttpRequestResultNormal) {
                                        [HFStatusView showSuccessMessage:kLocalizedString(@"提交成功",nil)];
                                        if ([[data[@"data"] allKeys]containsObject:@"asset"]) {
                                            [subscriber sendNext:[data[@"data"]objectForKey:@"asset"]];
                                        }else{
                                            [subscriber sendNext:@"-1"];
                                        }
                                        [subscriber sendCompleted];
                                    }else{
                                        [HFStatusView showFailureMessage:msg];
                                        [subscriber sendError:nil];
                                        [subscriber sendCompleted];
                                    }
                                }];
                            }else{
                                [self_weak_.viewControllers stopLoading];
                                [HFStatusView showFailureMessage:msg];
                                [subscriber sendError:nil];
                                [subscriber sendCompleted];
                            }
                        }];
                    }];
                    
                }else{
                    [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试",nil)];
                }
            }];
            
            return [RACDisposable disposableWithBlock:^{
                NSLog(@"提现操作结束了");
            }];
        }];
    }];
}

- (void)closeView {
    [self.alertView dismiss];
    [self.viewControllers.view endEditing:YES];
}

- (void)buttonEvent {
    NSString *password = self.rechargeTF.text;
    if ([password floatValue] <= 0) {
        return;
    }
    [self.viewControllers.view endEditing:YES];
    [self.alertView dismiss];
    
    __weak typeof(self)weakself = self;
    //校验支付密码
    [UserManager checkPayPassWordWithUserID:[CBTLocalUserManager sharedInstance].userId passWord:password block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal && [[data[@"data"]objectForKey:@"result"]boolValue] == YES) {
            //                    //转账
            //                    [UserManager userDoChangeWithUserID:[CBTLocalUserManager sharedInstance].userId coinId:self_weak_.coinId address:self_weak_.addressTextField.text value:self_weak_.amountTextField.text remark:[NSString excludeNullString:self_weak_.remarksTextField.text] feeRatio:self_weak_.costLabel.text block:^(id data, HttpRequestResult result, NSString *msg) {
            //                        [self_weak_ stopLoading];
            //                        if (result == kHttpRequestResultNormal) {
            //                            if (self_weak_.transferSuccessBlock != nil) {
            //                                self_weak_.transferSuccessBlock();
            //                            }
            //                            [HFStatusView showSuccessMessage:kLocalizedString(@"提交成功",nil)];
            //                            [self_weak_.navigationController popViewControllerAnimated:YES];
            //                        }else{
            //                            [HFStatusView showFailureMessage:msg];
            //                        }
            //                    }];
        }
        else {
            [weakself.viewControllers stopLoading];
            [HFStatusView showFailureMessage:msg];
        }
    }];
}
- (void)payOrder {
    
    
    JHUIAlertConfig *config = [[JHUIAlertConfig alloc] init];
    
    config.title.text  = kLocalizedString(@"校验支付密码", nil);
    config.title.color = UIColorFromRGB(0xff5101);
    config.title.bottomPadding = 100;
    config.dismissWhenTapOut   = NO;
    config.contentViewWidth    = SCREEN_WIDTH*0.8;
    config.contentViewHeight   = 180;
    self.alertView = [[JHUIAlertView alloc] initWithConfig:config];
    
    __weak typeof(self)weakself = self;
    [self.alertView addCustomView:^(JHUIAlertView *alertView, CGRect contentViewRect, CGRect titleLabelRect, CGRect contentLabelRect) {
        
        UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom];
        closebtn.tintColor = [UIColor blackColor];
        [closebtn setImage:[UIImage imageNamed:@"loginClose"] forState:UIControlStateNormal];
        [closebtn addTarget:weakself action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
        closebtn.frame = CGRectMake(contentViewRect.size.width-30, 10, 20, 20);
        [alertView.contentView addSubview:closebtn];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-30, 40)];
        textField.backgroundColor = UIColorFromRGB(0xEAEAEA);
        textField.keyboardType = UIKeyboardTypeDecimalPad;
        textField.layer.cornerRadius = 5;
        [alertView.contentView addSubview:textField];
        weakself.rechargeTF = textField;
        weakself.rechargeTF.placeholder = kLocalizedString(@"请输入支付密码", nil);
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(15, CGRectGetMaxY(textField.frame)+24, contentViewRect.size.width-30, 40);
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setTitle:kLocalizedString(@"确定", nil) forState:0];
        [button setTitleColor:[UIColor whiteColor] forState:0];
        button.layer.cornerRadius = 5;
        button.backgroundColor = UIColorFromRGB(0xff5001);
        [button addTarget:weakself action:@selector(buttonEvent) forControlEvents:1<<6];
        [alertView.contentView addSubview:button];
        
    }];
    
    [self.viewControllers.view addSubview:self.alertView];
    
    //输入支付
    @weak(self);
    [ZFPwdView showZFPwdViewWithInputCompletedBlock:^(NSString * _Nonnull password) {
        [self_weak_.viewControllers startClearBgColorLoading];
    }];
}

@end
